<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>利用Blob对象创建文件</title>
</head>

<body>
    <textarea name="" id="downloadFileTextarea" cols="30" rows="10"></textarea>
    <br>
    <button id="downloadFileButton">downloadFileButton</button>
    <script>
    // 利用Blob, a.download, URL.createObjectURL模拟下载文件
    function downloadFile(fileName, content, blobOptions) {

        // blobOptions = {
        //     type: 'text/csv',
        //     endings: 'native' // or transparent
        // };
        blobOptions = blobOptions || {};

        var blob = new Blob([content], blobOptions);
        var a = document.createElement('a');
        a.innerHTML = fileName;

        // 指定生成的文件名
        a.download = fileName;
        a.href = URL.createObjectURL(blob);

        document.body.appendChild(a);

        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", false, false);

        a.dispatchEvent(evt);

        document.body.removeChild(a);
    }

    downloadFileButton.onclick = function() {
        downloadFile('downloadFile.txt', downloadFileTextarea.value);
    };
    </script>
</body>

</html>